/*
	******************************************************************************************
	Post/View Photos - Use Case 6.1, 6.2:  by Brannen Sorem,  Last Updated 03/20/10 - 10:04am

	Functional Specification
	Photo.js is the javascript file that handles all of the interaction from the user for
	photos.php.  It adds the photo upload form and the photo gallery area to the page and it
	also adds the ability for a user to search and the AJAX request to photo_upload.php.  The 
	photos are stored on Flickr.com and accessed using a JSON request from a Flickr URL tied 
	to the account.  Posting photos is done through the Flickr API and uses a PHP library to 
	do so - phpFlickr.
	
	Web Master Maintenance:
	******************************************************************************************
	

	******************************************************************************************
*/

// for searching for username by tags
var testing = false;
var test;
var view_number = 8;

$(document).ready(function() {
	/////////////////////// CLEAN HOUSE /////////////////////////////////////
	// load images in gallery
	refresh();
	// hide response element (no responses yet)
	$("#response").hide();
	
	// add the photo upload function to the page if javascript enabled
	$("#photo_upload").append(upload_form);
	
	// if javascript not disabled, remove notice
	$("#grace_photo").remove();
	////////////////////////////////////////////////////////////////////////
	
	////////////////////////// USER ACTIONS ////////////////////////////////
	// upload photo using AJAX (using "jQuery Form plugin")
	var options = { success: showResponse }; 
    $('#photo_upload_form').submit(function() { 
		$("<div></div>").attr("id", "loading_icon")
			.append("<img src='images/loading.gif' alt='loading' />")
			.appendTo("#submit");
		$("#upload_photo_button").attr("disabled","disabled");
		$("#upload_photo_button").attr("value", "loading...");
        $(this).ajaxSubmit(options);
        return false; 
    }); 
	// response to AJAX request
	function showResponse(responseText, statusText, xhr, $form)  { 
		// put everything back together
		$("#upload_photo_button").attr("value", "Upload");
		$("#upload_photo_button").removeAttr("disabled");
		$("#loading_icon").remove();
		// if currently animating, STOP and replace with new message
		$("#response").stop().pause(200)
			.replaceWith('<div id="response"></div>')
		$("#response").html(responseText)
			.fadeIn(500)
			.pause(5000)
			.slideUp(300);
		// turn search off just in case (because the current action is UPLOAD)
		testing = false;
		refresh();
		// if uploaded, remove all info except name (tags) from form (to allow for another upload)
		if (responseText == "Photo uploaded!"){
			$("#title").val('');
			$("#description").val('');
			$("#file").val('');
		}
	}
	
	// ======= HELP link action info for Your Name in Upload photos ========================
	$("a#inline").fancybox({
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade',
		'scrolling'			: 'no',
		'titleShow'			: 'false',
		'overlayOpacity'	: 0.5,
		'overlayColor'		: "#000"
	});

	/////////////////////////////////////////////////////////////////////////
});

///////////////////////////// NON-USER ACTIONS //////////////////////////////
// add search field to gallery element
function add_search(){
	// add to gallery
	$(search_form).appendTo("#gallery");
	// add click functionality to refresh gallery with tags
	$("#search_button").click(function(){
		if ($("#search").val()){
			testing = true;
			test = $("#search").val();
			refresh();
		} else {
			testing = false;
			refresh();
		}
	});
	
	// ======= HELP button action info for View photos ========================
	$("#inline_help").fancybox({
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade',
		'scrolling'			: 'no',
		'titleShow'			: 'false',
		'overlayOpacity'	: 0.5,
		'overlayColor'		: "#000"
	});
	$("#help_button").click(function(){
		$("a#inline_help").click();
	});
}

// update the gallery images from Flickr using JSON
function refresh(){
	// get images from Flickr
	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?&id=48013477@N04&lang=en-us&format=json&jsoncallback=?", function(data){
		// clear out gallery to avoid infinite repetition
		$("#gallery").children().remove();
		var i = 0;
		var x = 0;
		var c = 0;
		$.each(data.items, function(i, item){
			// if you're trying to search
			if (testing){
				// see how many match the search query
				if (matching(test, item.tags)){ x++; }
			} else { x = 1; } // display all photos
		});
		// if there aren't any SEARCHED items, give error
		if (x == 0){
			test = test.replace(".", "\*");
			test = test.replace("+", "\ ");
			error = "No item(s) found: \"" + test + "\".  Click [Filter] to return.";
			$("<div></div>").html(error)
				.attr("id", "error")
				.appendTo("#gallery");
		} else { // either there are photos with search term, or no search term
	  	$.each(data.items, function(i,item){
			// number of photos to display
			if (i < view_number || (testing && c < view_number)){
				if (testing){
					if (matching(test, item.tags)){
						// add selected photo to gallery
				    	$("<img/>").attr("src", item.media.m)
							.attr("alt", item.title)
							.attr("class", "flickr_photo")
							.appendTo("#gallery")
							.wrap("<a href='" + item.media.m + "' rel='photo'></a>")
							.parent().attr("title", "<a href=" + item.link + ">" + item.title + "</a>");
						c++;
					}
				} else {
					// add all photos to gallery
			    	$("<img/>").attr("src", item.media.m)
						.attr("alt", item.title)
						.attr("class", "flickr_photo")
						.appendTo("#gallery")
						.wrap("<a href='" + item.media.m + "' rel='photo'></a>")
						.parent().attr("title", "<a href=" + item.link + ">" + item.title + "</a>");
				}
			}
		});
		}
		add_search();
		// create the view more photos link
		$("<div></div>").attr("id", "flickr_load")
			.append("<a href='http://www.flickr.com/photos/48013477@N04/'>view more...</a>")
			.appendTo("#gallery");
		// add neat photo click functionality (using Fancybox: http://fancybox.net/)
		$("#gallery a[rel=photo]").fancybox({
			'transitionIn'		: 'fade',
			'transitionOut'		: 'fade',
			'cyclic'			:  true,
			'titlePosition' 	: 'over',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
		});
	});
}
//////////////////////////////////////////////////////////////////////////////

// ////////////// Check to see if search cases match /////////////////////////
function matching(search, tag){
	var match = 0;
	var tags = tag;
	var searches = search;
	tags = tags.split(" "); // separate words from TAG string
	searches = searches.split(" "); // separate words from Search Query string
	
	// for each word in Flickr TAG
	for (x=0; x < tags.length; x++){
		// for each word in Search Query
		for (y=0; y < searches.length; y++){
			tags[x] = tags[x].toLowerCase();
			searches[y] = searches[y].toLowerCase();
			// see if they match
			if (tags[x].match(searches[y])){
				match++; // the words match
			}
		}
	}
	if (tags.length < searches.length) return false; // won't find a TAGs match smaller than the search query
	else if (tags.length >= searches.length && match >= searches.length) return true;
}

// custom pause function to delay between jQuery animation actions
$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};
